#!/bin/sh

# the defined variables should be:
# CONSPIRE_WRITEABLEDIR
# CONSPIRE_KEYID
# CONSPIRE_TMAX
# CONSPIRE_CLUSTERID
# CONSPIRE_DEMAND_JOB

export CONSPIRE_JOBID=$PBS_JOBID
if [ "$CONSPIRE_CLUSTERID" = "emerald" ]; then
   export CONSPIRE_JOBID=$LSB_JOBID
fi
cd $CONSPIRE_WRITEABLEDIR
if [ -n "`which wget`" ]; then
   wget http://$CONSPIRE_BROKERHOST:$CONSPIRE_BROKERPORT/hosted_files/_acquirepy -O acquirepy.tar.gz
else
   if [ -n "`which curl`" ]; then
      curl http://$CONSPIRE_BROKERHOST:$CONSPIRE_BROKERPORT/hosted_files/_acquirepy > acquirepy.tar.gz
   else
      echo "Could not find suitable downloading program!"
   fi
fi
# Can't go into the directory until it's safe
tar xvzf acquirepy.tar.gz -C $CONSPIRE_WRITEABLEDIR
sh ./binary_patch.sh _acquirepy.so python*
ln -s python* python
#chmod +x compute
mkdir work
echo $LD_LIBRARY_PATH
echo "Running: "
echo "LD_PRELOAD=glibc_patch.so LD_LIBRARY_PATH=. ./python -S compute.py \
  -n $CONSPIRE_BROKERHOST -p $CONSPIRE_BROKERPORT -d $PWD/work \
  -c \"$CONSPIRE_KEYID\" -u \"$CONSPIRE_KEYID\"_inp -r \"$CONSPIRE_KEYID\"_out \
  -j \"$CONSPIRE_JOBID\" -i \"$CONSPIRE_DEMAND_JOB\" -t \"$CONSPIRE_TMAX\""
LD_PRELOAD=glibc_patch.so LD_LIBRARY_PATH=. ./python -S compute.py \
  -n $CONSPIRE_BROKERHOST -p $CONSPIRE_BROKERPORT -d $PWD/work \
  -c "$CONSPIRE_KEYID" -u "$CONSPIRE_KEYID"_inp -r "$CONSPIRE_KEYID"_out \
  -j "$CONSPIRE_JOBID" -i "$CONSPIRE_DEMAND_JOB" -t "$CONSPIRE_TMAX"

# Actually, it may be an idea to leave everything on the compute
# (apart from the real work and keys) to facilitate debugging
#rm *.enc
#rm *.dec
#rm *.sgn
#rm *.chk
#rm password
#rm -fr work
#rm compute
#rm -f *.so*
#rm *.c
#rm *.o
#rm *.map
#rm binary_patch.sh
#rm compute.tar.gz
